# encoding: utf-8

from flask import Blueprint, render_template, request, current_app, url_for, flash, redirect, abort, make_response
# from bluelog.models import Post, Category, Comment, Admin
# from bluelog.forms import AdminCommentForm, CommentForm
# from bluelog.emails import send_new_comment_email
# from bluelog.extensions import db, current_user
import os, chardet

blog_bp = Blueprint('blog', __name__,
                    template_folder='templates', static_url_path='/static', static_folder='static')


@blog_bp.route('/')
def index():
    return blog_bp.send_static_file('index.html')


@blog_bp.route('/<value>/')
def md(value):
    return blog_bp.send_static_file(value+'/index.html')


@blog_bp.route('/search.html/<value>/', methods=['GET'])
def searchhtml_md(value):
    return redirect(url_for("blog.md", value=value))


@blog_bp.route('/search.html/', methods=['GET'])
def searchhtml():
    if len(request.args) == 0:
        return redirect(url_for("blog.index")) # reset index
    return blog_bp.send_static_file('search.html')


@blog_bp.route('/search.html/search.html', methods=['GET'])
@blog_bp.route('/search.html/search.html/', methods=['GET'])
def searchhtml2():
    return redirect(url_for("blog.searchhtml", q=request.args['q']))


@blog_bp.before_app_request
def before():
    # index
    if request.path == '/':
        return

    request.path = request.path[1:]
    # print('ask ', request.path, request.args, len(request.args))
    #
    # search src
    if 'lunr.js' in request.path or 'worker.js' in request.path \
            or 'main.js' in request.path\
            or 'search_index.json' in request.path:
        request.path = request.path.replace('search.html/', '')
        return blog_bp.send_static_file(request.path)

    # src
    if 'js/' in request.path\
            or 'css/' in request.path\
            or 'fonts/' in request.path\
            or 'img/' in request.path:
        request.path = request.path.replace('search.html/', '')
        return blog_bp.send_static_file(request.path)

    # search
    # if 'search.html/' in request.path:
    #     return
